package com.jucai.pppeiyouclient.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.WechatPay;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.PayResult;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.popup.PayWayPopup;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


public class RechargeActivity extends BaseActivity {
    private static final String TAG = "RechargeActivity : ";
    private static final int SDK_PAY_FLAG = 2001;
    private TextView rechargeWay, rechargeBankCard, rechargeCardLimit, rechargePay, rechargeZfb, rechargeWeChat;
    private EditText rechargeSum;
    private RelativeLayout bankCardRl;
    private PayWayPopup payPopup;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);

    private static Activity activity;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();

                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.showToast("支付成功");
                        rechargeSum.setText("0.00");
                    } else {

                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showToast("支付结果确认中");
                        } else {
                            ToastUtils.showToast("支付失败");
                        }

                    }
                    break;
                default:
                    break;
            }
        }
    };

    public static void payWxDone(boolean isSuccess) {
        if (activity != null && activity instanceof RechargeActivity) {
            if (isSuccess) {
                activity.setResult(RESULT_OK);
                ActivityCollector.removeActivity(activity);
            }
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recharge);
        activity = this;

        ((TextView) findViewById(R.id.common_title_text)).setText("充值");
        rechargeWay = (TextView) findViewById(R.id.recharge_way);
        rechargeSum = (EditText) findViewById(R.id.recharge_sum);
        rechargeZfb = (TextView) findViewById(R.id.recharge_zfb);
        rechargeWeChat = (TextView) findViewById(R.id.recharge_we_chat);
        rechargeBankCard = (TextView) findViewById(R.id.recharge_bank_card);
        rechargeCardLimit = (TextView) findViewById(R.id.recharge_card_limit);
        rechargePay = (TextView) findViewById(R.id.recharge_pay);
        bankCardRl = (RelativeLayout) findViewById(R.id.bank_card_rl);
        payPopup = new PayWayPopup(RechargeActivity.this, getWindow(), R.style.animBottomInBottomOut, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payPopup.dismiss();
                switch (view.getId()) {
                    case R.id.popup_we_chat:
                        rechargeWay.setText("微信");
                        bankCardRl.setVisibility(View.INVISIBLE);
                        rechargeZfb.setVisibility(View.GONE);
                        rechargeWeChat.setVisibility(View.VISIBLE);
                        break;
                    case R.id.popup_zfb:
                        rechargeWay.setText("支付宝");
                        bankCardRl.setVisibility(View.INVISIBLE);
                        rechargeZfb.setVisibility(View.VISIBLE);
                        rechargeWeChat.setVisibility(View.GONE);
                        break;
                    /*case R.id.popup_bank_card:
                        rechargeWay.setText("银行卡");
                        bankCardRl.setVisibility(View.VISIBLE);
                        rechargeZfb.setVisibility(View.GONE);
                        rechargeWeChat.setVisibility(View.GONE);
                        break;*/
                    default:
                        break;
                }

            }
        });

    }

    @Override
    protected void initData() {
       /* if (TextUtils.equals(rechargeWay.getText().toString(), "银行卡")) {
            bankCardRl.setVisibility(View.VISIBLE);
            rechargeZfb.setVisibility(View.GONE);
            rechargeWeChat.setVisibility(View.GONE);

        } else*/ if (TextUtils.equals(rechargeWay.getText().toString(), "支付宝")) {
            bankCardRl.setVisibility(View.INVISIBLE);
            rechargeZfb.setVisibility(View.VISIBLE);
            rechargeWeChat.setVisibility(View.GONE);
        } else if (TextUtils.equals(rechargeWay.getText().toString(), "微信")) {
            bankCardRl.setVisibility(View.INVISIBLE);
            rechargeZfb.setVisibility(View.GONE);
            rechargeWeChat.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        rechargeWay.setOnClickListener(this);
        rechargeBankCard.setOnClickListener(this);
        rechargePay.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(RechargeActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.recharge_way:
                payPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.recharge_bank_card:

                break;

            case R.id.recharge_pay:
                try {
                   double dPrice = Double.parseDouble(rechargeSum.getText().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showToast("请输入正确的数字");
                    break;
                }
                if (TextUtils.equals(rechargeSum.getText().toString(), "0.00")) {
                    ToastUtils.showToast("充值金额不能为0");
                } else{

                    if (rechargeWay.getText().toString().equals("支付宝")) {

                        HashMap<String, String> param = new HashMap<>();
                        param.put("credit", rechargeSum.getText().toString());
                        param.put("service", "Client_Wallet.recharge");
                        param.put("member_id", LoginUtils.getMember_id(this));
                        param.put("token", LoginUtils.getToken(this));
                        param.put("type","alipay");

                        CommonRequestNetData.getJsonString(RechargeActivity.this, true, param, new CommonRequestNetData.JsonStringCallBack() {
                            @Override
                            public void parseJsonString(String str) {
                                LogUtils.e(TAG + "str = " + str);
                                String sign = str;
                                zfbPay(sign);
                            }
                        });
                    } else if(rechargeWay.getText().toString().equals("微信")){
                        HashMap<String, String> param = new HashMap<>();
                        param.put("credit", rechargeSum.getText().toString());
                        param.put("service", "Client_Wallet.recharge");
                        param.put("member_id", LoginUtils.getMember_id(this));
                        param.put("token", LoginUtils.getToken(this));
                        param.put("type","weixin");

                        CommonRequestNetData.getJsonObjectData(this, true, param, new CommonRequestNetData.JsonObjectCallBack() {
                            @Override
                            public void parseJsonObject(JSONObject jsonObject) {
                                    WechatPay wechatPay = new Gson().fromJson(jsonObject.toString(), WechatPay.class);
                                    payWechat(wechatPay);
                            }
                        });
                       // ToastUtils.showToast("目前只支持支付宝支付，请选择支付宝支付");
                    }
                }
                break;
        }
    }

    private void zfbPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask aliPay = new PayTask(RechargeActivity.this);
                String result = aliPay.pay(orderInfo, true);
                LogUtils.e(TAG + "SDK 返回：" + result.toString());

                Message message = Message.obtain();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void payWechat(WechatPay pay) {
        PayReq req = new PayReq();
        req.appId = pay.AppID;
        req.partnerId = pay.PartnerId;
        req.prepayId = pay.PrepayId;
        req.packageValue = pay.PackageValue;
        req.nonceStr = pay.NonceStr;
        req.timeStamp = pay.TimeStamp;
        req.sign = pay.Sign;
        msgApi.registerApp(pay.AppID);
        msgApi.sendReq(req);
    }
}
